#include"Acceptor.h"

Acceptor::Acceptor(IMessageChannelFactory* pf,Selector* pSelector,IMessageSystem::CallBack::OnAccept a,void* pTag)
{
	m_pSelector = pSelector;
	m_pFactory = pf;
	m_OnAccept = a;
	m_pTag = pTag;
}

void Acceptor::Listen(const char* ip,unsigned short port,int backlog)
{
	m_socket = ::socket(AF_INET,SOCK_STREAM,0);
	sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port=::htons(port);
	addr.sin_addr.s_addr = inet_addr(ip);
	int err = bind(m_socket,(sockaddr*)&addr,sizeof(sockaddr_in));
	err = listen(m_socket,backlog);	
	m_pSelector->Register(m_socket);
}

void Acceptor::Poll()
{
	if(m_pSelector->CanRead(m_socket))
	{
		sockaddr_in addr;
		socklen_t len = sizeof(sockaddr_in);
		SOCKET client = accept(m_socket,(sockaddr*)&addr,&len);
		if(client != INVALID_SOCKET)
		{
			m_pSelector->Register(client);
			int err = setsockopt(client,SOL_SOCKET,0x700B,(char*)&m_socket,sizeof(m_socket));
			IMessageChannel* pClient = (IMessageChannel*)m_pFactory->Create(client);
			m_OnAccept(pClient,m_pTag);
		}
	}
}
